package com.antoco.operation.bigscreen.service.autogeneration.impl;

import com.antoco.operation.bigscreen.model.dto.SensorDTO;
import com.antoco.operation.bigscreen.model.entity.Sensor;
import com.antoco.operation.bigscreen.repository.SensorRepository;
import com.antoco.operation.bigscreen.service.WebSocketServer;
import com.antoco.operation.bigscreen.service.autogeneration.intf.SensorService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SensorServiceImpl extends AbstractModelServiceImpl implements SensorService {

    @Autowired
    private SensorRepository repository;

    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public Sensor save(Sensor entity) {
        repository.save(entity);
        dealSendData(entity);
        return entity;
    }

    @Override
    public List<Sensor> save(List<Sensor> entities) {
        return (List<Sensor>) repository.saveAll(entities);
    }

    @Override
    public void deleteById(Long id) {
        repository.deleteById(id);
    }

    @Override
    public Optional<Sensor> findById(Long id) {
        return repository.findById(id);
    }

    /**
     * 根据Sensor表的id查询对应的Sensor表List
     * @param id
     * @return
     */
    public List<Sensor> queryListById(Long id) {
        Optional<Sensor> sensoroOptional = findById(id);
        if (sensoroOptional.isPresent()){
            List<Sensor> sensorList = new ArrayList<Sensor>();
            Sensor sensor = sensoroOptional.get();
            sensorList.add(sensor);
            return sensorList;
        } else {
            return null;
        }
    }

    @Override
    public List<Sensor> findAll() {
        return (List<Sensor>) repository.findAll();
    }

    @Override
    public Page<Sensor> findAll(Pageable pageable) {
        Page<Sensor> entityPage = repository.findAll(pageable);
        List<Sensor> entities = entityPage.getContent();
        return new PageImpl<>(entities, pageable, entityPage.getTotalElements());
    }

    @Override
    public Sensor update(Sensor entity, Long id) {
        Optional<Sensor> optional = findById(id);
        if (optional.isPresent()) {
            Sensor originalSensor = optional.get();
            originalSensor.setDevBigType(entity.getDevBigType())
                .setDevBigTypeName(entity.getDevBigTypeName())
                .setDevType(entity.getDevType())
                .setDevTypeName(entity.getDevTypeName())
                .setName(entity.getName())
                .setGisName(entity.getGisName())
                .setGisJindu(entity.getGisJindu())
                .setGisWeidu(entity.getGisWeidu())
                .setState(entity.getState())
                .setStateName(entity.getStateName())
                .setXinhao(entity.getXinhao())
                .setXinhaoName(entity.getXinhaoName())
                .setTiaosi(entity.getTiaosi())
                .setTiaosiName(entity.getTiaosiName())
                .setBuildTime(entity.getBuildTime())
                .setCaosenboSuiwei(entity.getCaosenboSuiwei())
                .setYaliSuiwei(entity.getYaliSuiwei())
                .setHightForBottom(entity.getHightForBottom())
                .setSenyuDianlian(entity.getSenyuDianlian())
                .setValType(entity.getValType())
                .setValTypeName(entity.getValTypeName())
                .setAlarmLimitVal(entity.getAlarmLimitVal())
                .setWarnLimitVal(entity.getWarnLimitVal());

            return repository.saveAndFlush(originalSensor);
        }
        return null;
    }

    /**
     * 根据Sensor表的设备大类查询对应的Sensor表数据
     * @param devBigType
     * @return
     */
    public List<Sensor> queryListByCondition(String devBigType) {
        return repository.findBySensorBigType(devBigType);
    }

    /**
     * 根据传过来的Sensor实体对象，来处理消息推送
     * @param entity
     */
    public void dealSendData(Sensor entity){
        try {
            List<Sensor> list = queryListByCondition(entity.getDevBigType());
            String channelName = "";
            if ((entity.getDevBigType()).equals("1")) {
                channelName = "WATER_QUALITY";
            } else {
                channelName = "WATER_AMOUNT";
            }
            JSONArray jsonArray = JSONArray.fromObject(list);
            JSONObject json = new JSONObject();
            json.put("sensor", jsonArray);
            JSONObject result = new JSONObject();
            result.put("data", json);
            result.put("channel", channelName);
            // 推送给水质或水量频道
            webSocketServer.send2Channel(channelName, result.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}